﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LPY.Data.LeMongo
{
    using MongoDB.Bson;
    using MongoDB.Driver;
    using System.Configuration;

    public class MongoHelper<T>
    {
        private IMongoDatabase database = null;
        private IMongoClient client = null;
        private IMongoCollection<T> collection = null;

        #region 单例

        private static object asyncObj = new object();
        private static MongoHelper<T> instance;

        public static MongoHelper<T> Instance
        {
            get
            {
                if(null==instance)
                {
                lock (asyncObj)
                {
                    if(null==instance)
                    {
                        instance = new MongoHelper<T>();
                    }
                }
                }
                return instance;
            }
        }

        #endregion

        #region 属性
        private string connectionString;
        /// <summary>
        /// 连接字符串
        /// </summary>
        public string ConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(connectionString))
                {
                    connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
                }
                return connectionString;
            }
            set
            {
                connectionString = value;
            }
        }

        private string databaseName;
        /// <summary>
        /// 数据库名称
        /// </summary>
        public string DatabaseName
        {
            get
            {
                if(string.IsNullOrEmpty(databaseName))
                {
                    databaseName = ConfigurationManager.AppSettings["MongoDatabaseName"];
                }
                return databaseName;
            }
            set
            {
                databaseName = value;
            }
        }

        public IMongoDatabase Database
        {
            get
            {
                return database;
            }
        }

        public IMongoClient Client
        {
            get
            {
                return client;
            }
        }

        public IMongoCollection<T> Collection
        {
            get
            {
                return collection;
            }
        }

        #endregion

        #region 构造函数

        private MongoHelper()
        {
            client = new MongoClient(ConnectionString);
            database = client.GetDatabase(DatabaseName);
            collection = database.GetCollection<T>(typeof(T).Name);
        }

        #endregion

        #region 增

        public void Insert<T>(string collectionName,T model)
            where T:EntityBase
        {
            if(null==model)
            {
                throw new ArgumentException("model", "插入实体不能为Null");
            }
            var collection = database.GetCollection<T>(collectionName);
            collection.InsertOne(model);
        }

        #endregion

        #region 删

        public void DeleteByObjectId(string id)
        {
            ObjectId objId;
            if(!ObjectId.TryParse(id,out objId))
            {
                throw new ArgumentException("id", "ObjectId格式不正确！");
            }
            //todo
        }

        #endregion

        #region 改
        public bool Update<T>(string connectionString,string dbName,string collectionName,FilterDefinition<T> filter,UpdateDefinition<T> update,T model)
        {
            var collection=database.GetCollection<T>(collectionName);
            var result= collection.UpdateOne(filter, update);
            return result.ModifiedCount > 0;
        }
        #endregion

        #region 查

        /// <summary>
        /// 通过主键查找
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public T FindById<T>(string collectionName,string id)
            where T:EntityBase
        {
            var oid=ObjectId.Parse(id);
            var collection= database.GetCollection<T>(collectionName);
            return collection.Find<T>(m=>m.Id==oid).Single<T>();
        }

        public List<T> Find<T>(string collectionName, FilterDefinition<T> filter)
        {
            var collection = database.GetCollection<T>(collectionName);
            return collection.Find<T>(filter).ToList<T>();
        }

        /// <summary>
        /// 按主键分页查找
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<T> FindByPager<T>(string collectionName,int pageIndex,int pageSize)
            where T:EntityBase
        {
            var collection = database.GetCollection<T>(collectionName);
            return collection.AsQueryable().OrderBy(m => m.Id).Skip(pageIndex * pageSize).Take(pageSize).ToList<T>();
        }

        #endregion

    }
}
